package com.sita.bike.ui.activity.roadtrust;

import android.content.Context;
import android.content.Intent;
import android.content.pm.PackageInfo;
import android.content.pm.PackageManager;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.graphics.drawable.BitmapDrawable;
import android.net.Uri;
import android.os.Bundle;
import android.util.Log;
import android.view.Gravity;
import android.view.KeyEvent;
import android.view.View;
import android.view.ViewGroup;
import android.view.animation.AnimationUtils;
import android.widget.Button;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.PopupWindow;
import android.widget.RelativeLayout;
import android.widget.TextView;
import android.widget.Toast;

import com.amap.api.location.AMapLocation;
import com.amap.api.maps.AMap;
import com.amap.api.maps.CameraUpdate;
import com.amap.api.maps.CameraUpdateFactory;
import com.amap.api.maps.TextureMapView;
import com.amap.api.maps.model.BitmapDescriptorFactory;
import com.amap.api.maps.model.CameraPosition;
import com.amap.api.maps.model.LatLng;
import com.amap.api.maps.model.LatLngBounds;
import com.amap.api.maps.model.Marker;
import com.amap.api.maps.model.MarkerOptions;
import com.amap.api.navi.AMapNavi;
import com.amap.api.navi.AMapNaviListener;
import com.amap.api.navi.enums.PathPlanningStrategy;
import com.amap.api.navi.model.AMapLaneInfo;
import com.amap.api.navi.model.AMapNaviCross;
import com.amap.api.navi.model.AMapNaviInfo;
import com.amap.api.navi.model.AMapNaviLocation;
import com.amap.api.navi.model.AMapNaviPath;
import com.amap.api.navi.model.AMapNaviTrafficFacilityInfo;
import com.amap.api.navi.model.NaviInfo;
import com.amap.api.navi.model.NaviLatLng;
import com.amap.api.navi.view.RouteOverLay;
import com.amap.api.services.core.LatLonPoint;
import com.autonavi.tbt.TrafficFacilityInfo;
import com.sita.bike.R;
import com.sita.bike.support.Constants;
import com.sita.bike.support.GlobalContext;
import com.sita.bike.utils.AccountUtils;
import com.sita.bike.utils.BitmapUtils;
import com.sita.tboard.ActivityBase;

import java.net.URISyntaxException;
import java.util.ArrayList;
import java.util.List;

/**
 * 创建时间：11/11/15 17:32
 * 项目名称：newNaviDemo
 *
 * @author lingxiang.wang
 * @email lingxiang.wang@alibaba-inc.com
 * 类说明：
 */

public class NavigateActivity extends ActivityBase implements AMapNaviListener {
    private static final int TAKE_LOCATION = 0x000002;
    private String locationlab;
    private LatLonPoint latLonPoint;
    // 地图和导航资源
    private TextureMapView mMapView;
    private AMap mAMap;
    private Marker destionationMarker;
    private MarkerOptions destionationMarkerOption;
    private Button cancelSendDestination;
    private ImageView routePlan, cancelRoutePlan;
    private RelativeLayout titleBar, routePlanBar;
    private TextView lab;
    private PopupWindow routePlanPop = null;
    private LinearLayout layoutRoutePlanPopup;
    private View parentView;
    // 起点终点坐标
    private NaviLatLng mNaviStart = new NaviLatLng(39.989614, 116.481763);
    private NaviLatLng mNaviEnd = new NaviLatLng(39.983456, 116.3154950);
    // 起点终点列表
    private ArrayList<NaviLatLng> mStartPoints = new ArrayList<>();
    private ArrayList<NaviLatLng> mEndPoints = new ArrayList<>();
    // 规划线路
    private RouteOverLay mRouteOverLay;
    private AMapNavi aMapNavi;


    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        parentView = getLayoutInflater().inflate(R.layout.activity_navigate, null);
        setContentView(parentView);
        locationlab = getIntent().getStringExtra("myLocation");
        latLonPoint = getIntent().getParcelableExtra("latLonPoint");
        initView(savedInstanceState);
        calculateDriveRoute(latLonPoint);
    }

    // 初始化View
    private void initView(Bundle savedInstanceState) {
        titleBar = (RelativeLayout) findViewById(R.id.layout_title_bar);
        routePlanBar = (RelativeLayout) findViewById(R.id.layout_route_plan_bar);
        lab = (TextView) findViewById(R.id.txt_lab);
        lab.setText(locationlab);
        cancelSendDestination = (Button) findViewById(R.id.btn_cancel_send);
        cancelSendDestination.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                finish();
            }
        });

        cancelRoutePlan = (ImageView) findViewById(R.id.cancel_route_plan);
        cancelRoutePlan.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                finish();
            }
        });


        routePlanPop = new PopupWindow(this);
        View routePlanView = getLayoutInflater().inflate(R.layout.popup_windows_route_plan, null);
        layoutRoutePlanPopup = (LinearLayout) routePlanView.findViewById(R.id.layout_route_plan_popup);

        routePlanPop.setWidth(ViewGroup.LayoutParams.MATCH_PARENT);
        routePlanPop.setHeight(ViewGroup.LayoutParams.WRAP_CONTENT);
        routePlanPop.setBackgroundDrawable(new BitmapDrawable());
        routePlanPop.setFocusable(true);
        routePlanPop.setOutsideTouchable(true);
        routePlanPop.setContentView(routePlanView);

        RelativeLayout routePlanParent = (RelativeLayout) routePlanView.findViewById(R.id.route_plan_parent);
        LinearLayout selfRoutePlan =(LinearLayout) routePlanView.findViewById(R.id.layout_self_route_plan) ;
        TextView devider = (TextView)routePlanView.findViewById(R.id.devider);
        Button toAmap = (Button) routePlanView.findViewById(R.id.btn_to_amap);
        Button toBaidu = (Button) routePlanView.findViewById(R.id.btn_to_baidu_map);
        Button routePlanCancel = (Button) routePlanView.findViewById(R.id.btn_route_plan_cancel);
        routePlanParent.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                routePlanPop.dismiss();
                layoutRoutePlanPopup.clearAnimation();
            }
        });
        selfRoutePlan.setVisibility(View.GONE);
        devider.setVisibility(View.GONE);
        toAmap.setOnClickListener(new View.OnClickListener() {
            public void onClick(View v) {
                //测试跳转第三方
                if (isAvilible(getApplicationContext(), "com.autonavi.minimap")) {//传入指定应用包名
                    Intent intent = null;
                    try {
                        String poiname = null;
                        String lat = null;
                        String lon = null;
                        if (latLonPoint != null) {
                            poiname = locationlab;
                            lat = String.valueOf(latLonPoint.getLatitude());
                            lon = String.valueOf(latLonPoint.getLongitude());

                        }
                        intent = Intent.getIntent("androidamap://viewMap?sourceApplication=摩趣&poiname=" + poiname +
                                "&lat=" + lat +
                                "&lon=" + lon + "&dev=0");
                        startActivity(intent); //启动调用
                    } catch (URISyntaxException e) {
                        Log.e("intent", e.getMessage());
                    }
                } else {//未安装
                    Uri uri = Uri.parse("market://details?id=com.autonavi.minimap");
                    Intent intent = new Intent(Intent.ACTION_VIEW, uri);
                    startActivity(intent);
                }
                routePlanPop.dismiss();
                layoutRoutePlanPopup.clearAnimation();

            }
        });
        toBaidu.setOnClickListener(new View.OnClickListener() {
            public void onClick(View v) {
                if (isAvilible(getApplicationContext(), "com.baidu.BaiduMap")) {//传入指定应用包名
                    Intent intent = null;
                    try {
                        AMapLocation location = GlobalContext.getLocationClient().getLastKnownLocation();
                        String latLngStart = "latlng:" + location.getLatitude() + "," + location.getLongitude();
                        String latLngEnd = null;
                        if (latLonPoint != null) {
                            latLngEnd = "latlng:" + String.valueOf(latLonPoint.getLatitude()) + "," + String.valueOf(latLonPoint.getLongitude());
                        }
                        intent = Intent.getIntent("intent://map/direction?" +
                                "origin=" + latLngStart + "|name:起点&" +
                                "destination=" + latLngEnd + "|name:终点&" +
                                "&mode=driving&" + //导航方式
                                "&src=com.sita.bike#Intent;scheme=bdapp;package=com.baidu.BaiduMap;end");
                        startActivity(intent); //启动调用
                    } catch (URISyntaxException e) {
                        Log.e("intent", e.getMessage());
                    }
                } else {//未安装
                    //market为路径，id为包名
                    //显示手机上所有的market商店
                    Uri uri = Uri.parse("market://details?id=com.baidu.BaiduMap");
                    Intent intent = new Intent(Intent.ACTION_VIEW, uri);
                    startActivity(intent);
                }
                routePlanPop.dismiss();
                layoutRoutePlanPopup.clearAnimation();
            }
        });


        routePlanCancel.setOnClickListener(new View.OnClickListener() {
            public void onClick(View v) {
                routePlanPop.dismiss();
                layoutRoutePlanPopup.clearAnimation();
            }
        });


        //点击按钮弹出pop,选择导航方式
        routePlan = (ImageView) findViewById(R.id.btn_route_plan);
        routePlan.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                layoutRoutePlanPopup.startAnimation(AnimationUtils.loadAnimation(getApplicationContext(), R.anim.activity_translate_in));
                routePlanPop.showAtLocation(parentView, Gravity.BOTTOM, 0, 0);
            }
        });

        mMapView = (TextureMapView) findViewById(R.id.mapview);
        mMapView.onCreate(savedInstanceState);
        initMap();


    }

    protected void initMap() {
        if (mAMap == null) {
            mAMap = mMapView.getMap();
        }
        aMapNavi = AMapNavi.getInstance(this);
        aMapNavi.addAMapNaviListener(this);
        aMapNavi.setEmulatorNaviSpeed(150);
        mRouteOverLay = new RouteOverLay(mAMap, null);
    }


    @Override
    public boolean onKeyDown(int keyCode, KeyEvent event) {
        if (keyCode == KeyEvent.KEYCODE_BACK) {
            finish();
        }
        return super.onKeyDown(keyCode, event);
    }

    @Override
    public void onResume() {
        super.onResume();
        mMapView.onResume();
    }

    @Override
    public void onPause() {
        super.onPause();
        mMapView.onPause();
    }

    @Override
    public void onDestroy() {
        super.onDestroy();
        mMapView.onDestroy();
    }


    /**
     * * 检查手机上是否安装了指定的软件
     * * @param context
     * * @param packageName：应用包名
     * * @return
     */
    private boolean isAvilible(Context context, String packageName) {
        //获取packagemanager
        final PackageManager packageManager = context.getPackageManager();
        //获取所有已安装程序的包信息
        List<PackageInfo> packageInfos = packageManager.getInstalledPackages(0);
        //用于存储所有已安装程序的包名
        List<String> packageNames = new ArrayList<String>();
        List<String> mappackages = new ArrayList<String>();
        //从pinfo中将包名字逐一取出，压入pName list中
        if (packageInfos != null) {
            for (int i = 0; i < packageInfos.size(); i++) {
                String packName = packageInfos.get(i).packageName;
                packageNames.add(packName);
            }
        }
        //判断packageNames中是否有目标程序的包名，有TRUE，没有FALSE
        return packageNames.contains(packageName);
    }

    @Override
    public void onInitNaviFailure() {

    }

    @Override
    public void onInitNaviSuccess() {

    }

    @Override
    public void onStartNavi(int i) {

    }

    @Override
    public void onTrafficStatusUpdate() {

    }

    @Override
    public void onLocationChange(AMapNaviLocation aMapNaviLocation) {

    }

    @Override
    public void onGetNavigationText(int i, String s) {

    }

    @Override
    public void onEndEmulatorNavi() {

    }

    @Override
    public void onArriveDestination() {

    }

    @Override
    public void onCalculateRouteSuccess() {

        AMapNaviPath naviPath = aMapNavi.getNaviPath();
        if (naviPath == null) {
            return;
        }
        // 获取路径规划线路，显示到地图上
        mRouteOverLay.setAMapNaviPath(naviPath);
        final String myAvatarUrl = AccountUtils.getAvatar();
        Bitmap myAvatar = AccountUtils.getUserAvatar(myAvatarUrl);
        mRouteOverLay.setStartPointBitmap(BitmapUtils.zoomBitmap(BitmapFactory.decodeResource(getResources(), R.drawable.location_a),100,100));
        mRouteOverLay.setEndPointBitmap(BitmapUtils.zoomBitmap(BitmapFactory.decodeResource(getResources(), R.drawable.location_b),100,100));
        mRouteOverLay.addToMap();
        LatLng startLatLng = new LatLng(mNaviStart.getLatitude(),mNaviStart.getLongitude());
        LatLng endLatLng = new LatLng(mNaviEnd.getLatitude(),mNaviEnd.getLongitude());
        LatLngBounds bounds = new LatLngBounds.Builder()
                .include(startLatLng).include(endLatLng).build();
        mAMap.moveCamera(CameraUpdateFactory.newLatLngBounds(bounds, 150));

    }

    @Override
    public void onCalculateRouteFailure(int i) {

    }

    @Override
    public void onReCalculateRouteForYaw() {

    }

    @Override
    public void onReCalculateRouteForTrafficJam() {

    }

    @Override
    public void onArrivedWayPoint(int i) {

    }

    @Override
    public void onGpsOpenStatus(boolean b) {

    }

    @Override
    public void onNaviInfoUpdated(AMapNaviInfo aMapNaviInfo) {

    }

    @Override
    public void onNaviInfoUpdate(NaviInfo naviInfo) {

    }

    @Override
    public void OnUpdateTrafficFacility(TrafficFacilityInfo trafficFacilityInfo) {

    }

    @Override
    public void OnUpdateTrafficFacility(AMapNaviTrafficFacilityInfo aMapNaviTrafficFacilityInfo) {

    }

    @Override
    public void showCross(AMapNaviCross aMapNaviCross) {

    }

    @Override
    public void hideCross() {

    }

    @Override
    public void showLaneInfo(AMapLaneInfo[] aMapLaneInfos, byte[] bytes, byte[] bytes1) {

    }

    @Override
    public void hideLaneInfo() {

    }

    @Override
    public void onCalculateMultipleRoutesSuccess(int[] ints) {

    }

    @Override
    public void notifyParallelRoad(int i) {

    }

    //计算驾车路线
    private void calculateDriveRoute(LatLonPoint latLonPoint) {
        //当前位置为开始位置
        AMapLocation location = GlobalContext.getLocationClient().getLastKnownLocation();
        mNaviStart.setLatitude(location.getLatitude());
        mNaviStart.setLongitude(location.getLongitude());
        //搜索位置为结束位置
        mNaviEnd.setLatitude(latLonPoint.getLatitude());
        mNaviEnd.setLongitude(latLonPoint.getLongitude());
        mStartPoints.clear();
        mEndPoints.clear();
        mStartPoints.add(mNaviStart);
        mEndPoints.add(mNaviEnd);
        boolean isSuccess = aMapNavi.calculateDriveRoute(mStartPoints,
                mEndPoints, null, PathPlanningStrategy.DRIVING_DEFAULT);
        if (!isSuccess) {
            Toast.makeText(this, "路线计算失败,检查参数情况", Toast.LENGTH_SHORT);
        }

    }
}